import 'package:auto_size_text/auto_size_text.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:xingsu/page/publisher/activity_more_page.dart';
import 'package:xingsu/page/publisher/detail_page.dart';
import 'package:xingsu/page/publisher/new_more_page.dart';
import 'package:xingsu/page/publisher/task_search_page.dart';
import 'package:xingsu/page/publisher/viewModel/publisher_viewmodel.dart';
import 'package:xingsu/util/app_util.dart';
import 'package:xingsu/util/image_util.dart';
import 'package:get/get.dart';
import 'package:xingsu/util/widget_util.dart';
import 'package:xingsu/widget/search_widget.dart';

import '../../res/colors.dart';

class PublisherPage extends StatefulWidget {
  const PublisherPage({Key? key}) : super(key: key);

  @override
  State<PublisherPage> createState() => _PublisherPageState();
}

class _PublisherPageState extends State<PublisherPage>
    with AutomaticKeepAliveClientMixin {
  final PublisherViewModel _viewModel = Get.put(PublisherViewModel());

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 0,
      ),
      body: SafeArea(
          child: SmartRefresher(
        controller: _viewModel.refreshController,
        enablePullDown: true,
        enablePullUp: true,
        header: const WaterDropHeader(),
        onRefresh: _viewModel.loadData,
        onLoading: _viewModel.loadMore,
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: Column(
            children: [
              _topWidget(),
              _bannerWidget(),
              _newWidget(),
              // _activityWidget(),
              _recommendWidget()
            ],
          ),
        ),
      )),
    );
  }

  Widget _topWidget() {
    return SearchWidget(
      placeholder: "搜索任务",
      controller: TextEditingController(),
      onSubmitted: (_) {},
      clickCallback: () {
        Get.to(() => TaskSearchPage());
      },
    );
  }

  Widget _bannerContainer() {
    Map map = _viewModel.banner1;
    Map detail_info = map["detail_info"] ?? {};
    Map data = detail_info["data"] ?? {};
    Map taskInfo = data["task_info"];
    return Container(
      margin: const EdgeInsets.only(top: 20),
      height: 204,
      child: Row(
        children: [
          Expanded(
              flex: 158,
              child: InkWell(
                onTap: () {
                  Get.to(() => DetailPage(map));
                },
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Container(
                    height: 204,
                    color: Colours.textColor,
                    child: Stack(
                      children: [
                        SizedBox(
                          height: 175,
                          child: ConstrainedBox(
                            constraints: const BoxConstraints.expand(),
                            child: Opacity(
                              opacity: 0.7,
                              child: loadNetworkImage(
                                  taskInfo["HorizontalPicture"]),
                            ),
                          ),
                        ),
                        const Positioned(
                            top: 10,
                            left: 10,
                            child: Text(
                              "创意内容",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.w700),
                            )),
                        Positioned(
                          bottom: 0,
                          left: 0,
                          child:
                              loadAssetImage("icon_new", height: 35, width: 46),
                        ),
                        Positioned(
                            left: 60,
                            right: 0,
                            bottom: 5,
                            child: Text(
                              taskInfo["TaskName"],
                              maxLines: 1,
                              style: const TextStyle(color: Colors.white),
                            )),
                        Align(
                          alignment: Alignment.center,
                          child: loadAssetImage("icon_play",
                              width: 36, height: 36),
                        )
                      ],
                    ),
                  ),
                ),
              )),
          const SizedBox(
            width: 10,
          ),
          Expanded(
              flex: 170,
              child: Column(
                children: [
                  _bannerItemWidget(_viewModel.banner2),
                  const SizedBox(
                    height: 10,
                  ),
                  _bannerItemWidget(_viewModel.banner3),
                ],
              ))
        ],
      ),
    );
  }

  Widget _bannerWidget() {
    return Obx(() =>
        _viewModel.banner1.isEmpty ? const SizedBox() : _bannerContainer());
  }

  Widget _bannerItemWidget(Map map) {
    Map detail_info = map["detail_info"] ?? {};
    Map data = detail_info["data"] ?? {};
    Map taskInfo = data["task_info"] ?? {};
    Map taskStat = taskInfo["TaskStat"] ?? {};
    String gameName = taskInfo["GameName"] ?? "";
    String icon = taskInfo["GameIcon"] ?? "";
    String info = "${taskStat["UserCount"] ?? 0}人参与";
    return Expanded(
      child: InkWell(
        onTap: () {
          Get.to(() => DetailPage(map));
        },
        child: ClipRRect(
          borderRadius: BorderRadius.circular(10),
          child: Container(
            color: Colours.textColor,
            child: Stack(
              alignment: Alignment.centerLeft,
              children: [
                Positioned(
                  right: 0,
                  bottom: 0,
                  child: Container(
                    alignment: Alignment.center,
                    height: 52,
                    width: 100,
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage(getImgPath("banner_mask")),
                            fit: BoxFit.fill)),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          gameName.length > 5
                              ? gameName.substring(0, 5)
                              : gameName,
                          style: const TextStyle(
                              fontSize: 13, color: Colors.white),
                        ),
                        const SizedBox(
                          height: 8,
                        ),
                        Text(
                          info,
                          style: const TextStyle(
                              fontSize: 11, color: Colours.grayColor),
                        )
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 8),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(10),
                        child: loadNetworkImage(icon, width: 76, height: 76),
                      ),
                      const SizedBox(
                        width: 10,
                      ),
                      Row(
                        children: [
                          loadAssetImage("icon_mark", width: 10, height: 10),
                          const SizedBox(
                            width: 5,
                          ),
                          const Text(
                            "优质游戏",
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 11,
                                fontWeight: FontWeight.w700),
                          )
                        ],
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _newWidget() {
    return Obx(() => _viewModel.recentList.isEmpty
        ? const SizedBox()
        : Column(
            children: [
              _titleWidget("最近上新", clickCallback: () {
                Get.to(() => NewMorePage());
              }),
              SizedBox(
                width: double.infinity,
                height: 100,
                child: ListView(
                  scrollDirection: Axis.horizontal,
                  children: _viewModel.recentList
                      .map((element) => _newItemWidget(element))
                      .toList(),
                ),
              )
            ],
          ));
  }

  Widget _newItemWidget(Map map) {
    Map task_info = map["task_info"];
    Map detail_info = map["detail_info"] ?? {};
    Map data = detail_info["data"] ?? {};
    Map taskInfo = data["task_info"];

    return InkWell(
      onTap: () {
        Get.to(() => DetailPage(map));
      },
      child: Container(
        width: 60,
        margin: const EdgeInsets.only(right: 10),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(3),
              child: loadNetworkImage(task_info["game_icon"] ?? "",
                  width: 60, height: 60),
            ),
            const SizedBox(
              height: 2,
            ),
            Text(
              task_info["task_name"] ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(fontSize: 10),
            ),
            const SizedBox(
              height: 2,
            ),
            Text(
              AppUtil.convertEpochToMonthDay(taskInfo["StartTime"] ??
                  DateTime.now().millisecondsSinceEpoch / 1000),
              style: const TextStyle(color: Color(0xFFB4B6C1), fontSize: 10),
            )
          ],
        ),
      ),
    );
  }

  Widget _titleWidget(String title, {VoidCallback? clickCallback}) {
    return Container(
      height: 60,
      alignment: Alignment.centerLeft,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: const TextStyle(
              fontSize: 17,
            ),
          ),
          clickCallback == null
              ? const SizedBox()
              : InkWell(
                  onTap: clickCallback,
                  child: Row(
                    children: [
                      const Text(
                        "更多",
                        style: TextStyle(color: Colors.grey, fontSize: 12),
                      ),
                      loadAssetImage("arrow_right", width: 12)
                    ],
                  ),
                )
        ],
      ),
    );
  }

  Widget _activityWidget() {
    bool isDark = context.isDarkMode;

    return Obx(() => _viewModel.activityList.isEmpty
        ? const SizedBox()
        : Column(
            children: [
              _titleWidget("活动大厅", clickCallback: () {
                Get.to(() => const ActivityMorePage());
              }),
              SizedBox(
                width: double.infinity,
                height: 110,
                child: Swiper(
                  itemCount: _viewModel.activityList.length,
                  autoplay: true,
                  itemBuilder: (context, index) {
                    Map map = _viewModel.activityList[index];
                    return Container(
                      alignment: Alignment.centerLeft,
                      padding: const EdgeInsets.all(15),
                      decoration: BoxDecoration(
                          color: isDark
                              ? Colours.dark_material_bg
                              : Colours.bg_gray,
                          borderRadius: BorderRadius.circular(5)),
                      child: Row(
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(5),
                            child: loadNetworkImage(
                              map["ActivityBanner"] ?? "",
                              width: 100,
                            ),
                          ),
                          const SizedBox(
                            width: 10,
                          ),
                          Expanded(
                              child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                map["ActivityName"] ?? "",
                                maxLines: 1,
                                style: const TextStyle(fontSize: 15),
                              ),
                              const SizedBox(
                                height: 10,
                              ),
                              Row(
                                children: [
                                  WidgetUtil.processingStatusWidget(
                                      map["ProcessingStatus"] ?? 1),
                                  const SizedBox(
                                    width: 5,
                                  ),
                                  Expanded(
                                      child: Text(
                                    "${AppUtil.timeStringFromTime(map["ActivityBeginTime"] ?? 0)}-${AppUtil.timeStringFromTime(map["ActivityEndTime"] ?? 0)}",
                                    maxLines: 1,
                                    style: const TextStyle(fontSize: 12),
                                  ))
                                ],
                              ),
                              const SizedBox(
                                height: 10,
                              ),
                              Text(
                                "${map["Award"] ?? ""} | 热度：${AppUtil.convertWan(map["ActivityHotValue"] ?? 0)}",
                                maxLines: 1,
                                style: const TextStyle(
                                    color: Colors.grey, fontSize: 12),
                              )
                            ],
                          ))
                        ],
                      ),
                    );
                  },
                ),
              )
            ],
          ));
  }

  Widget _recommendWidget() {
    return Obx(() => _viewModel.recommendList.isEmpty
        ? const SizedBox()
        : Column(children: [
            _titleWidget("任务推荐"),
            GridView.count(
              crossAxisCount: 2,
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              mainAxisSpacing: 8,
              crossAxisSpacing: 8,
              childAspectRatio: 1,
              children: _viewModel.recommendList
                  .map((element) => _recommendItemWidget(element))
                  .toList(),
            )
          ]));
  }

  Widget _recommendItemWidget(Map map) {
    bool isDark = context.isDarkMode;

    Map activityInfo = map["activity_info"] ?? {};
    Map taskInfo = map["task_info"] ?? {};

    String banner = activityInfo["activity_horizontal_picture"] ??
        (taskInfo["horizontal_picture"] ?? "");
    String info = "";

    if (taskInfo["user_count"] != null) {
      info = "${AppUtil.convertWan(taskInfo["user_count"])}人投稿";
    }

    if (activityInfo["activity_hot_value"] != null) {
      info =
          "热度${AppUtil.convertWan(activityInfo["activity_hot_value"], hasDecimal: false)}";
    }

    String bottom = "";
    bool hasActivity = activityInfo.isNotEmpty;
    if (hasActivity) {
      bottom = activityInfo["activity_name"] ?? "";
    } else {
      bottom = "￥${taskInfo["recent_max_task_income"] ?? 0}";
    }

    return InkWell(
      onTap: () {
        Get.to(() => DetailPage(map));
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(5),
        child: Container(
          color: isDark ? Colours.dark_material_bg : Colours.bg_gray,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: ConstrainedBox(
                  constraints: const BoxConstraints.expand(),
                  child: loadNetworkImage(banner, fit: BoxFit.cover),
                ),
              ),
              const SizedBox(
                height: 8,
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8),
                child: Row(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(10),
                      child: loadNetworkImage(taskInfo["game_icon"] ?? "",
                          width: 40, height: 40),
                    ),
                    const SizedBox(
                      width: 8,
                    ),
                    Expanded(
                        child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          taskInfo["task_name"] ?? "",
                          maxLines: 1,
                          style: const TextStyle(fontSize: 13),
                        ),
                        const SizedBox(
                          height: 4,
                        ),
                        Text(
                          info,
                          maxLines: 1,
                          style:
                              const TextStyle(color: Colors.grey, fontSize: 9),
                        )
                      ],
                    ))
                  ],
                ),
              ),
              // const SizedBox(
              //   height: 8,
              // ),
              // Padding(
              //   padding: const EdgeInsets.symmetric(horizontal: 8),
              //   child: Text.rich(TextSpan(children: [
              //     TextSpan(
              //       text: hasActivity ? "" : "当前最高收益：",
              //       style: const TextStyle(color: Colors.grey, fontSize: 12),
              //     ),
              //     TextSpan(
              //       text: bottom,
              //       style: const TextStyle(fontSize: 12),
              //     )
              //   ])),
              // ),
              const SizedBox(
                height: 10,
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
